<template>
  <!--  -->
  <div class="chat-box" @mousemove="readedMessage()" @click="closeRefBox()">
    <el-container class="chat-container">
      <ChatTop
        :chat="chat"
        :groupMembers="groupMembers"
        @setSideStatus="setSideStatus"
      />
      <el-main style="padding: 0" class="chat-main">
        <el-container>
          <el-container class="content-box">
            <ChatMessageList
              ref="chatMessageListRef"
              :chat="chat"
              @showBannedTip="showBannedTip"
            />
            <el-footer height="220px" class="im-chat-footer">
              <ChatTools :chat="chat" :isBanned="isBanned" ref="chatToolsRef" />
              <div class="send-content-area">
                <ChatInput
                  :ownerId="group.ownerId"
                  ref="chatInputEditorRef"
                  :group-members="groupMembers"
                  @submit="sendMessage"
                />
                <div class="send-btn-area">
                  <el-button
                    type="primary"
                    icon="el-icon-s-promotion"
                    @click="notifySend()"
                    >发送</el-button
                  >
                </div>
              </div>
            </el-footer>
          </el-container>
          <el-aside class="side-box" width="320px" v-if="showSide">
            <ChatGroupSide
              :group="group"
              :groupMembers="groupMembers"
              @reload="loadGroup(group.id)"
            />
          </el-aside>
        </el-container>
      </el-main>

      <!--
      <chat-record
        :visible="showRecord"
        @close="closeRecordBox"
        @send="onSendRecord"
      ></chat-record>
      <group-member-selector
        ref="rtcSel"
        :group="group"
        @complete="onInviteOk"
      ></group-member-selector>
      <rtc-group-join ref="rtcJoin" :groupId="group.id"></rtc-group-join>
      <chat-history
        :visible="showHistory"
        :chat="chat"
        :friend="friend"
        :group="group"
        :groupMembers="groupMembers"
        @close="closeHistoryBox"
      ></chat-history> -->
    </el-container>
  </div>
</template>

<script setup lang="ts">
import http from "@/utils/request";
import { MESSAGE_TYPE } from "@/types/enums";
import { useChatStore } from "@/store/modules/chatStore";
import { useUserStore } from "@/store/modules/userStore";
const chatStore = useChatStore();
const userStore = useUserStore();
// const chat = {} as any;
const props = defineProps({
  chat: Object as any,
});
const groupMembers = [] as any;
// 是否显示群聊信息栏
const showSide = ref(false);
const isReceipt = ref(false);
const lockMessage = ref(false); // 是否锁定发送
const group = ref({}) as any;
const userInfo = ref({}) as any;

const chatInputEditorRef = ref(null);
const chatToolsRef = ref(null);
const chatMessageListRef = ref(null);
const isBanned = computed(() => {
  return (
    (props.chat.type == "PRIVATE" && userInfo.value.isBanned) ||
    (props.chat.type == "GROUP" && group.value.isBanned)
  );
});
const mine = computed(() => {
  return userStore.userInfo;
});
function closeRefBox() {
  chatToolsRef.value?.closeRefBox();
}
// 消息已读
function readedMessage() {
  if (props.chat.unreadCount == 0) {
    return;
  }
  chatStore.resetUnreadCount(props.chat);
  if (props.chat.type == "GROUP") {
    var url = `/message/group/readed?groupId=${props.chat.targetId}`;
  } else {
    url = `/message/private/readed?friendId=${props.chat.targetId}`;
  }
  // http({
  //   url: url,
  //   method: "put",
  // }).then(() => {});
}
function setSideStatus() {
  showSide.value != showSide.value;
}
function notifySend() {
  chatInputEditorRef.value?.submit();
}
function loadGroup(groupId: Number) {
  // this.$http({
  //   url: `/group/find/${groupId}`,
  //   method: "get",
  // }).then((group) => {
  //   this.group = group;
  //   this.chatStore.updateChatFromGroup(group);
  //   this.groupStore.updateGroup(group);
  // });
  // this.$http({
  //   url: `/group/members/${groupId}`,
  //   method: "get",
  // }).then((groupMembers) => {
  //   this.groupMembers = groupMembers;
  // });
}

async function sendMessage(fullList: any) {
  resetEditor();
  readedMessage();
  // 检查是否被封禁
  if (isBanned.value) {
    showBannedTip();
    return;
  }
  let sendText = isReceipt.value ? "【回执消息】" : "";
  fullList.forEach(async (msg: any) => {
    switch (msg.type) {
      case "text":
        await sendTextMessage(sendText + msg.content, msg.atUserIds);
        break;
      case "image":
        await sendImageMessage(msg.content.file);
        break;
      case "file":
        await sendFileMessage(msg.content.file);
        break;
    }
  });
}

function sendFileMessage(file: any) {
  return new Promise((resolve, reject) => {
    // let check = this.$refs.fileUpload.beforeUpload(file);
    // if (check) {
    //   this.$refs.fileUpload.onFileUpload({ file });
    // }
  });
}
function sendImageMessage(file: any) {
  return new Promise((resolve, reject) => {
    // this.onImageBefore(file);
    // let formData = new FormData();
    // formData.append("file", file);
    // this.$http
    //   .post("/image/upload", formData, {
    //     headers: {
    //       "Content-Type": "multipart/form-data",
    //     },
    //   })
    //   .then((data) => {
    //     this.onImageSuccess(data, file);
    //     resolve();
    //   })
    //   .catch((res) => {
    //     this.onImageFail(res, file);
    //     reject();
    //   });
    // this.$nextTick(() => this.$refs.chatInputEditor.focus());
    // this.scrollToBottom();
  });
}
function sendTextMessage(sendText: string, atUserIds: any) {
  return new Promise((resolve, reject) => {
    if (!sendText.trim()) {
      reject();
    }
    let msgInfo = {
      content: sendText,
      type: 0,
      atUserIds: [],
      receipt: undefined as any,
    };
    // 填充对方id
    fillTargetId(msgInfo, props.chat.targetId);
    // 被@人员列表
    if (props.chat.type == "GROUP") {
      msgInfo.atUserIds = atUserIds;
      msgInfo.receipt = isReceipt.value;
    }
    lockMessage.value = true;
    sendMessageRequest(msgInfo)
      .then((m: any) => {
        m.selfSend = true;
        chatStore.insertMessage(m, props.chat);
        // 会话置顶
        moveChatToTop();
      })
      .finally(() => {
        // 解除锁定
        chatMessageListRef.value?.scrollToBottom();
        isReceipt.value = false;
        resolve("");
      });
  });
}
function moveChatToTop() {
  // let chatIdx = chatStore.findChatIdx(props.chat);
  // chatStore.moveTop(chatIdx);
}
function sendMessageRequest(msgInfo: any) {
  return new Promise((resolve, reject) => {
    // 请求入队列，防止请求"后发先至"，导致消息错序
    // this.reqQueue.push({ msgInfo, resolve, reject });
    processReqQueue();
  });
}
function processReqQueue() {
  // if (this.reqQueue.length && !this.isSending) {
  //   this.isSending = true;
  //   const reqData = this.reqQueue.shift();
  //   this.$http({
  //     url: this.messageAction,
  //     method: "post",
  //     data: reqData.msgInfo,
  //   })
  //     .then((res) => {
  //       reqData.resolve(res);
  //     })
  //     .catch((e) => {
  //       reqData.reject(e);
  //     })
  //     .finally(() => {
  //       this.isSending = false;
  //       // 发送下一条请求
  //       this.processReqQueue();
  //     });
  // }
}
function fillTargetId(msgInfo: any, targetId: number) {
  if (props.chat.type == "GROUP") {
    msgInfo.groupId = targetId;
  } else {
    msgInfo.recvId = targetId;
  }
}
function showBannedTip() {
  let msgInfo = {
    tmpId: generateId(),
    sendId: mine.value.id,
    sendTime: new Date().getTime(),
    type: MESSAGE_TYPE.TIP_TEXT,
  } as any;
  if (props.chat.type == "PRIVATE") {
    msgInfo.recvId = mine.value.id;
    msgInfo.content = "该用户已被管理员封禁,原因:" + userInfo.value.reason;
  } else {
    msgInfo.groupId = group.value.id;
    msgInfo.content = "本群聊已被管理员封禁,原因:" + group.value.reason;
  }
  chatStore.insertMessage(msgInfo, props.chat);
}
function generateId() {
  // 生成临时id
  return (
    String(new Date().getTime()) + String(Math.floor(Math.random() * 1000))
  );
}
// 重置输入框
function resetEditor() {
  nextTick(() => {
    chatInputEditorRef.value?.clear();
    chatInputEditorRef.value?.focus();
  });
}
</script>

<style lang="scss" scoped>
.chat-box {
  position: relative;
  width: 100%;
  background: #fff;
  .chat-container {
    display: flex;
    flex-direction: column;
  }
  .chat-main {
    flex: 1;
  }
  .content-box {
    position: relative;

    .im-chat-footer {
      display: flex;
      flex-direction: column;
      padding: 0;

      .send-content-area {
        position: relative;
        display: flex;
        flex-direction: column;
        height: 100%;
        background-color: white !important;

        .send-btn-area {
          padding: 10px;
          position: absolute;
          bottom: 4px;
          right: 6px;
        }
      }
    }
  }

  .side-box {
    border-left: var(--im-border);
  }
}
</style>
